<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加按钮权限 </button>
                <button class="layui-btn layui-btn-sm layui-btn-warm data-delete-btn" lay-event="reload"> 刷新表格 </button>
            </div>
        </script>

        <table class="layui-hide" id="permsTableId" lay-filter="employeeTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>

<div class="layui-form layuimini-form" id="permsAddDiv" lay-filter="permsFilter" style="display: none;text-aglin:center">
    <div class="layui-form-item">
        <label class="layui-form-label required">按钮名称</label>
        <div class="layui-inline">
            <input type="hidden" name="menuId" />
            <input type="text" name="menuName" lay-verify="required" lay-reqtext="按钮名称不可为空" placeholder="请输入按钮名称" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">按钮权限描述</label>
        <div class="layui-inline">
            <input type="text" name="menuDetails" lay-verify="required" lay-reqtext="按钮权限描述不可为空" placeholder="请输入按钮权限描述" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">按钮权限url</label>
        <div class="layui-inline">
            <input type="text" name="menuUrl" lay-verify="required" lay-reqtext="按钮权限url不可为空" placeholder="请输入按钮权限url" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">按钮权限字符串</label>
        <div class="layui-inline">
            <input type="text" name="perms" lay-verify="required" lay-reqtext="按钮权限字符串不能为空" placeholder="请输入按钮权限字符串" value="" class="layui-input">
            <tip>格式:employee:add (员工新增按钮)</tip>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">选择角色</label>
        <div class="layui-inline" id="roleCheckBox" style="width: 50%;">

        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
    </div>
</div>

<script src="/static/admin/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table','jquery'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;

        table.render({
            elem: '#permsTableId',
            url: '/admin/queryPermsPage',
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            cols: [
                [
                {type: "checkbox"},
                {field: 'menuId', hide:true},
                {field: 'menuName', title: '权限按钮名称'},
                {field: 'menuDetails',title: '按钮描述'},
                {field:'menuUrl',title:'权限url'},
                {field: 'perms',title: '权限字符串'},
                {title: '按钮可见角色',templet:function (res) {
                        var html ='';

                        $.each(res.roleList,function (index,item) {
                            html +='<span class="layui-badge layui-bg-orange">'+item.roleName+'</span> ';
                        })
                        return html;

                    }},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]
            ],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true
        });

        //监听表单提交事件
        form.on('submit(saveBtn)', function(data){
            var url = "";
            if ($("input[name='menuId']").val().trim() == ""){
                url = '/admin/addPerms';
            }else{
                url = '/admin/updatePerms';
            }

            //将页面全部复选框选中的值拼接到一个数组中
            var arr_box = [];
            $("input[name='roleId']:checked").each(function() {
                arr_box.push($(this).val());
            });
            if (arr_box.length < 1 ){
                layer.msg("必须选择一个角色哟")
                return false;
            }
            data.field.roleIdList = arr_box.join("-");

            //添加按钮权限 ajax
            $.ajax({
                url:url,
                type:'post',
                data:data.field,
                dataType:'json',
                success:function (res) {
                    if (res.code == 200){
                        layer.msg(res.message+",即将刷新",function () {
                            //刷新表格
                            table.reload('permsTableId', {
                                url: '/admin/queryPermsPage'

                            });
                        });
                    }else{
                        layer.msg(res.message)
                    }


                }
            })

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            layer.alert(result, {
                title: '最终的搜索信息'
            });

            //执行搜索重载
            table.reload('permsTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    searchParams: result
                }
            }, 'data');

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(employeeTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作

                var index = layer.open({
                    title: '添加按钮权限',
                    type: 1,
                    area: ['600px', '600px'],
                    content: $('#permsAddDiv'),
                    success:function () {

                        $("input[name='menuName']").val("");
                        $("input[name='menuDetails']").val("");
                        $("input[name='menuUrl']").val("");
                        $("input[name='perms']").val("");
                        $("input[name='menuId']").val("");

                        //刷新出复选框
                        $.ajax({
                            url:'/admin/queryAllRole',
                            type:'post',
                            dataType:'json',
                            success:function (res) {
                                var html = '';
                                $.each(res.data,function (index,item) {
                                    html += '<input type="checkbox" name="roleId" title="'+item.roleName+'" value="'+item.roleId+'">';
                                })

                                $('#roleCheckBox').html(html);

                                form.render(); //更新全部
                            }
                        })

                    }
                });

            } else if (obj.event === 'reload') {  // 监听删除操作
                var checkStatus = table.checkStatus('permsTableId')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
        });

        //监听表格复选框选择
        table.on('checkbox(employeeTableFilter)', function (obj) {
            console.log(obj)
        });
        //表格行监听
        table.on('tool(employeeTableFilter)', function (obj) {
            var data = obj.data;

            if (obj.event === 'edit') {

                var index = layer.open({
                    title: '修改按钮权限',
                    type: 1,
                    area: ['600px', '600px'],
                    content: $('#permsAddDiv'),
                    success:function () {
                        $("input[name='menuId']").val(data.menuId);
                        //刷新出复选框
                        $.ajax({
                            url:'/admin/queryAllRole',
                            type:'post',
                            dataType:'json',
                            async:false, //同步值
                            success:function (res) {
                                var html = '';
                                $.each(res.data,function (index,item) {
                                    html += '<input type="checkbox" name="roleId" lay-filter="checkboxFilter" title="'+item.roleName+'" value="'+item.roleId+'" data-id="'+data.menuId+'">';
                                })

                                $('#roleCheckBox').html(html);

                                form.render(); //更新全部
                            }
                        })

                        //给表单赋值
                        form.val("permsFilter", data);
                        //获取已选中复选框
                        var roleList = data.roleList;
                        var roleAllList = [];
                        //给复选框赋值
                        $("input:checkbox[name='roleId']").each(function (index,item) {
                            var value = $(this).val();

                            var count =0;
                            for (var j=0;roleList.length>j;j++){

                                if (value == roleList[j].roleId){
                                    count++;

                                }

                            }

                            if (count >0){

                                $(this).prop("checked",true);
                            }

                        })


                        form.render(); //更新全部

                    }
                });

                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除按钮权限么', function (index) {

                    $.ajax({
                        url:'/admin/deletePerms/'+data.menuId,
                        type:'post',
                        dataType:'json',
                        success:function (res) {

                            if (res.code==200){
                                obj.del();

                            }

                            layer.msg(res.message)

                        }
                    })

                    layer.close(index);
                });
            }
        });

        //复选框监听
        form.on('checkbox(checkboxFilter)', function(data){

            //获取菜单id
            var elem = data.elem;

            console.log(elem.getAttribute("data-id"))

            var check = data.elem.checked;
            //赋予角色
            if (check){
                addMenuRole("/admin/addMenuRole/"+elem.getAttribute("data-id")+"/"+data.value);

            }else{//删除角色
                addMenuRole("/admin/deleteMenuRole/"+elem.getAttribute("data-id")+"/"+data.value);
            }


        });

        //添加角色菜单表
        function addMenuRole(url) {

            $.ajax({
                url: url,
                type:'post',
                dataType:'',
                success:function (res) {

                    layer.msg(res.message+",即将刷新",function () {
                        //刷新表格
                        table.reload('permsTableId', {
                            url: '/admin/queryPermsPage'

                        });
                    });

                }
            })

        }

    });
</script>

</body>
</html>
